<template>
  <div class="parcel-manager">
    <!-- 地块管理面板 -->
    <div class="parcel-panel" :class="{ collapsed: panelCollapsed }">
      <div class="panel-header">
        <h3>地块管理</h3>
        <button class="collapse-btn" @click="togglePanel">
          {{ panelCollapsed ? '展开' : '收起' }}
        </button>
      </div>
      
      <div class="panel-content" v-if="!panelCollapsed">
        <div class="action-section">
          <button @click="refreshParcels" class="refresh-btn">刷新地块</button>
          <button @click="toggleShowParcels" class="toggle-btn" 
                  :class="{ active: showParcels }">
            {{ showParcels ? '隐藏地块' : '显示地块' }}
          </button>
        </div>
        
        <!-- 地块列表 -->
        <div class="parcel-list">
          <div 
            v-for="parcel in parcels" 
            :key="parcel.id"
            class="parcel-item"
            :class="{ selected: selectedParcelId === parcel.id }"
            @click="selectParcel(parcel)"
          >
            <div class="parcel-info">
              <div class="parcel-name">{{ parcel.parcelName }}</div>
              <div class="parcel-details">
                <div class="detail-item">
                  <span class="label">土壤类型:</span>
                  <span class="value">{{ parcel.soilType || '未知' }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">面积:</span>
                  <span class="value">{{ formatArea(parcel.area) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">创建时间:</span>
                  <span class="value">{{ formatTime(parcel.createdTime) }}</span>
                </div>
              </div>
            </div>
            <div class="parcel-actions">
              <button @click.stop="flyToParcel(parcel)" class="action-btn">
                定位
              </button>
              <button @click.stop="calculateWorkingArea(parcel)" class="action-btn">
                作业分析
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 作业面积分析结果面板 -->
    <div class="analysis-panel" v-if="showAnalysis">
      <div class="panel-header">
        <h4>作业面积分析 - {{ selectedParcel?.parcelName }}</h4>
        <button @click="closeAnalysis" class="close-btn">×</button>
      </div>
      
      <div class="analysis-content">
        <div class="analysis-summary">
          <div class="summary-item">
            <span class="label">地块总面积:</span>
            <span class="value">{{ formatArea(selectedParcel?.area) }}</span>
          </div>
          <div class="summary-item">
            <span class="label">已作业面积:</span>
            <span class="value">{{ formatArea(workingAreaResult.workingArea) }}</span>
          </div>
          <div class="summary-item">
            <span class="label">作业覆盖率:</span>
            <span class="value">{{ workingAreaResult.coverageRate }}%</span>
          </div>
        </div>
        
        <div class="device-analysis" v-if="workingAreaResult.deviceAnalysis.length > 0">
          <h5>设备作业详情:</h5>
          <div 
            v-for="device in workingAreaResult.deviceAnalysis" 
            :key="device.deviceId"
            class="device-item"
          >
            <div class="device-name">{{ device.deviceName }}</div>
            <div class="device-stats">
              <span>作业面积: {{ formatArea(device.workingArea) }}</span>
              <span>轨迹长度: {{ formatDistance(device.trackLength) }}</span>
            </div>
          </div>
        </div>
        
        <div class="analysis-actions">
          <button @click="exportAnalysisResult" class="export-btn">
            导出报告
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { parcelAPI, pathAPI, deviceAPI } from '../services/api.js';
import { DataUtils, SpatialUtils } from '../utils/dataUtils.js';
import * as Cesium from 'cesium';

// Props
const props = defineProps({
  viewer: {
    type: Object,
    required: true
  }
});

// Reactive data
const parcels = ref([]);
const selectedParcelId = ref(null);
const selectedParcel = ref(null);
const panelCollapsed = ref(false);
const showParcels = ref(true);
const showAnalysis = ref(false);

// 分析结果
const workingAreaResult = reactive({
  workingArea: 0,
  coverageRate: 0,
  deviceAnalysis: []
});

// 存储地块实体引用
const parcelEntities = new Map();

// Methods
const togglePanel = () => {
  panelCollapsed.value = !panelCollapsed.value;
};

const refreshParcels = async () => {
  try {
    parcels.value = await parcelAPI.getAllParcels();
    if (showParcels.value) {
      updateParcelEntities();
    }
  } catch (error) {
    console.error('获取地块列表失败:', error);
  }
};

const toggleShowParcels = () => {
  showParcels.value = !showParcels.value;
  if (showParcels.value) {
    updateParcelEntities();
  } else {
    clearParcelEntities();
  }
};

const selectParcel = (parcel) => {
  selectedParcelId.value = parcel.id;
  selectedParcel.value = parcel;
};

const flyToParcel = (parcel) => {
  if (!parcel.parcelBoundary) return;
  
  const hierarchy = DataUtils.polygonToHierarchy(parcel.parcelBoundary);
  if (hierarchy) {
    const rectangle = Cesium.Rectangle.fromCartesianArray(hierarchy.positions);
    props.viewer.camera.flyTo({
      destination: rectangle,
      duration: 2.0
    });
  }
};

const calculateWorkingArea = async (parcel) => {
  selectedParcel.value = parcel;
  showAnalysis.value = true;
  
  try {
    // 获取地块边界
    const parcelHierarchy = DataUtils.polygonToHierarchy(parcel.parcelBoundary);
    if (!parcelHierarchy) {
      console.warn('无效的地块边界数据');
      return;
    }
    
    // 获取所有设备
    const devices = await deviceAPI.getAllDevices();
    
    // 重置分析结果
    workingAreaResult.workingArea = 0;
    workingAreaResult.coverageRate = 0;
    workingAreaResult.deviceAnalysis = [];
    
    // 分析每个设备的作业情况
    for (const device of devices) {
      const deviceAnalysis = await analyzeDeviceWorkingArea(device, parcelHierarchy.positions);
      if (deviceAnalysis.workingArea > 0) {
        workingAreaResult.deviceAnalysis.push(deviceAnalysis);
        workingAreaResult.workingArea += deviceAnalysis.workingArea;
      }
    }
    
    // 计算覆盖率
    if (parcel.area && parcel.area > 0) {
      workingAreaResult.coverageRate = Math.min(
        ((workingAreaResult.workingArea / parcel.area) * 100),
        100
      ).toFixed(2);
    }
    
  } catch (error) {
    console.error('作业面积分析失败:', error);
  }
};

const analyzeDeviceWorkingArea = async (device, parcelPositions) => {
  const result = {
    deviceId: device.id,
    deviceName: device.deviceName,
    workingArea: 0,
    trackLength: 0
  };
  
  try {
    // 获取设备的所有路径
    const paths = await pathAPI.getPathsByDeviceId(device.id);
    
    for (const path of paths) {
      if (!path.pathPoints || path.pathPoints.length < 2) continue;
      
      // 将路径点转换为Cesium坐标
      const trackPositions = path.pathPoints.map(point => 
        Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude, 0)
      );
      
      // 计算轨迹长度
      for (let i = 0; i < trackPositions.length - 1; i++) {
        result.trackLength += Cesium.Cartesian3.distance(
          trackPositions[i], 
          trackPositions[i + 1]
        );
      }
      
      // 计算作业面积（假设作业宽度为5米）
      const workingArea = SpatialUtils.calculateWorkingArea(
        trackPositions, 
        parcelPositions, 
        5
      );
      result.workingArea += workingArea;
    }
    
  } catch (error) {
    console.error(`分析设备 ${device.deviceName} 作业面积失败:`, error);
  }
  
  return result;
};

const closeAnalysis = () => {
  showAnalysis.value = false;
};

const exportAnalysisResult = () => {
  if (!selectedParcel.value) return;
  
  const report = {
    parcel: {
      name: selectedParcel.value.parcelName,
      area: selectedParcel.value.area,
      soilType: selectedParcel.value.soilType
    },
    analysis: {
      totalWorkingArea: workingAreaResult.workingArea,
      coverageRate: workingAreaResult.coverageRate,
      analysisTime: new Date().toISOString()
    },
    devices: workingAreaResult.deviceAnalysis
  };
  
  // 导出为JSON文件
  const blob = new Blob([JSON.stringify(report, null, 2)], { 
    type: 'application/json' 
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `作业分析报告_${selectedParcel.value.parcelName}_${formatTime(new Date())}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const updateParcelEntities = () => {
  // 清除旧的地块实体
  clearParcelEntities();
  
  // 添加新的地块实体
  parcels.value.forEach(parcel => {
    if (!parcel.parcelBoundary) return;
    
    const hierarchy = DataUtils.polygonToHierarchy(parcel.parcelBoundary);
    if (!hierarchy) return;
    
    const entity = props.viewer.entities.add({
      id: 'parcel_' + parcel.id,
      name: parcel.parcelName,
      polygon: {
        hierarchy: hierarchy,
        material: Cesium.Color.fromAlpha(Cesium.Color.YELLOW, 0.3),
        outline: true,
        outlineColor: Cesium.Color.YELLOW,
        height: 0
      },
      label: {
        text: parcel.parcelName,
        font: '14px sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        position: Cesium.BoundingSphere.fromPoints(hierarchy.positions).center,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
      }
    });
    
    parcelEntities.set(parcel.id, entity);
  });
};

const clearParcelEntities = () => {
  parcelEntities.forEach(entity => props.viewer.entities.remove(entity));
  parcelEntities.clear();
};

const formatArea = (area) => {
  if (!area) return '0 平方米';
  if (area >= 10000) {
    return `${(area / 10000).toFixed(2)} 公顷`;
  } else {
    return `${area.toFixed(2)} 平方米`;
  }
};

const formatDistance = (distance) => DataUtils.formatDistance(distance || 0);
const formatTime = (time) => DataUtils.formatDateTime(time);

// 生命周期
onMounted(() => {
  refreshParcels();
  // 默认显示地块
  setTimeout(() => {
    if (parcels.value.length > 0) {
      showParcels.value = true;
      updateParcelEntities();
    }
  }, 1000);
});

// 对外暴露方法
defineExpose({
  refreshParcels,
  updateParcelEntities,
  clearParcelEntities
});
</script>

<style scoped>
.parcel-manager {
  position: relative;
  z-index: 1000;
}

.parcel-panel {
  position: absolute;
  bottom: 10px;
  left: 10px;
  width: 350px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.parcel-panel.collapsed {
  width: 150px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
}

.collapse-btn {
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.collapse-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.panel-content {
  padding: 15px;
  max-height: 50vh;
  overflow-y: auto;
}

.action-section {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.refresh-btn, .toggle-btn {
  flex: 1;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.refresh-btn {
  background: #007bff;
  color: white;
}

.refresh-btn:hover {
  background: #0056b3;
}

.toggle-btn {
  background: #6c757d;
  color: white;
}

.toggle-btn.active {
  background: #28a745;
}

.toggle-btn:hover {
  background: #5a6268;
}

.toggle-btn.active:hover {
  background: #218838;
}

.parcel-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.parcel-item {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 12px;
  cursor: pointer;
  transition: background 0.2s ease;
}

.parcel-item:hover {
  background: rgba(255, 255, 255, 0.2);
}

.parcel-item.selected {
  background: rgba(255, 193, 7, 0.3);
  border: 1px solid #ffc107;
}

.parcel-info {
  margin-bottom: 10px;
}

.parcel-name {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 8px;
  color: #ffc107;
}

.parcel-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
}

.detail-item .label {
  color: #ccc;
}

.detail-item .value {
  color: white;
  font-weight: 500;
}

.parcel-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
  padding: 6px 10px;
  background: #17a2b8;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.action-btn:hover {
  background: #138496;
}

.analysis-panel {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 400px;
  background: rgba(0, 0, 0, 0.9);
  color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.analysis-panel .panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 193, 7, 0.2);
}

.analysis-panel .panel-header h4 {
  margin: 0;
  font-size: 14px;
  color: #ffc107;
}

.close-btn {
  background: transparent;
  border: none;
  color: white;
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.analysis-content {
  padding: 15px;
}

.analysis-summary {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 15px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 13px;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-item .label {
  color: #ccc;
}

.summary-item .value {
  color: #ffc107;
  font-weight: bold;
}

.device-analysis {
  margin-bottom: 15px;
}

.device-analysis h5 {
  margin: 0 0 10px 0;
  font-size: 13px;
  color: #ffc107;
}

.device-analysis .device-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 6px;
}

.device-analysis .device-item:last-child {
  margin-bottom: 0;
}

.device-analysis .device-name {
  font-weight: bold;
  font-size: 12px;
  margin-bottom: 4px;
  color: white;
}

.device-stats {
  display: flex;
  justify-content: space-between;
  font-size: 11px;
  color: #ccc;
}

.analysis-actions {
  text-align: center;
}

.export-btn {
  padding: 8px 20px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.export-btn:hover {
  background: #218838;
}
</style>